package com.venue.hjt.venueclass.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.*
import com.google.gson.Gson

import com.venue.hjt.venueclass.R
import com.venue.hjt.venueclass.adapter.*
import com.venue.hjt.venueclass.bean.API
import com.venue.hjt.venueclass.bean.GroupBean
import com.venue.hjt.venueclass.bean.VenueBean
import com.venue.hjt.venueclass.bean.VenueChoiceBean
import com.venue.hjt.venueclass.db.CardDao
import com.venue.hjt.venueclass.utlis.*
import com.venue.hjt.venueclass.view.MyDialog
import com.venue.hjt.venueclass.view.MyGridView
import com.zhy.http.okhttp.OkHttpUtils
import kotlinx.android.synthetic.main.activity_venue_order.*
import okhttp3.Call
import org.jetbrains.anko.runOnUiThread
import java.util.*
import kotlin.collections.ArrayList

class VenueOrderActivity : AppCompatActivity() {
    var s=0
    var t=-1
    var venue_id=""
    var group_id=""
    var venue_name=""
    var group_name=""
    var venue_num=""
    var venue_student=""
    var VenueOrderTime=ClassCalendar.getStringVenueOrder1(0)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar!!.hide()
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        setContentView(R.layout.activity_venue_order)
        record=OrderReceiver1()
        registerReceiver(record,filter())
        venue_student=intent.getStringExtra("student_no")
        OkhttPost.Okget(API.VENUENUM + Constant.SNO, 1, object : OkhttPost.Callback {
            override fun onError(call: Call, e: Exception, id: Int) {

            }
            override fun onResponse(response: String, id: Int) {
                val gson=Gson()
                try{
                    val bean = gson.fromJson(response, VenueChoiceBean::class.java)
                    if (bean.code==1){
//                    val list=ArrayList<VenueChoiceBean.Data>()
                        for (i in 0 until bean.data.size) {
                            if (i==0){
                                bean.data[i].setIs(true)
                                venue_id= bean.data[i].id
                                venue_name=bean.data[i].venue_name
                                val queryVenueInfo = CardDao.queryVenueInfo()
                                val score=if (queryVenueInfo.size!=0)queryVenueInfo[0].getScore()else "0"
                                venue_num="(可容纳人数 "+bean.data[i].min_num+"～"+bean.data[i].max_num+"人 预约消耗"+score+"积分)"
                            }else{
                                bean.data[i].setIs(false)
                            }
                        }
                        setOk(gson,bean.data[0].id,ClassCalendar.getStringVenueOrder1(0))
                        val adapter=VenueOrderAdapter(this@VenueOrderActivity,bean.data)
                        gv_venue_x.adapter=adapter
                        gv_venue_x.setOnItemClickListener { adapterView, view, po, l ->
                            for(i in 0 until bean.data.size){
                                if (i==po){
                                    bean.data[i].setIs(true)
                                    s=po
                                    venue_id= bean.data[i].id
                                    venue_name=bean.data[i].venue_name
                                    val queryVenueInfo = CardDao.queryVenueInfo()
                                    val score=if (queryVenueInfo.size!=0)queryVenueInfo[0].getScore()else "0"
                                    venue_num="(可容纳人数 "+bean.data[i].min_num+"～"+bean.data[i].max_num+"人 预约消耗"+score+"积分)"
                                    getOk(gson,bean.data[i].id,ClassCalendar.getStringVenueOrder1(0))
                                    tab_order_menu.check( R.id.rb__order_time01)
                                }else{
                                    bean.data[i].setIs(false)
                                }
                            }
                            adapter.notifyDataSetChanged()
                        }
                        tab_order_menu.setOnCheckedChangeListener({ group, checkedId ->
                            when (checkedId) {
                                R.id.rb__order_time01 -> {
                                    getOk(gson,bean.data[s].id,ClassCalendar.getStringVenueOrder1(0))
                                    VenueOrderTime=ClassCalendar.getOldDate1(0)
                                }
                                R.id.rb__order_time02 -> {
                                    getOk(gson,bean.data[s].id,ClassCalendar.getStringVenueOrder1(1))
                                    VenueOrderTime=ClassCalendar.getOldDate1(1)
                                }
                                R.id.rb__order_time03 -> {
                                    getOk(gson,bean.data[s].id,ClassCalendar.getStringVenueOrder1(2))
                                    VenueOrderTime=ClassCalendar.getOldDate1(2)
                                }
                                R.id.rb__order_time04 -> {
                                    getOk(gson,bean.data[s].id,ClassCalendar.getStringVenueOrder1(3))
                                    VenueOrderTime=ClassCalendar.getOldDate1(3)
                                }
                                R.id.rb__order_time05 -> {
                                    getOk(gson,bean.data[s].id,ClassCalendar.getStringVenueOrder1(4))
                                    VenueOrderTime=ClassCalendar.getOldDate1(4)
                                }
                                R.id.rb__order_time06 -> {
                                    getOk(gson,bean.data[s].id,ClassCalendar.getStringVenueOrder1(5))
                                    VenueOrderTime=ClassCalendar.getOldDate1(5)
                                }
                                R.id.rb__order_time07 -> {
                                    getOk(gson,bean.data[s].id,ClassCalendar.getStringVenueOrder1(6))
                                    VenueOrderTime=ClassCalendar.getOldDate1(6)
                                }

                            }
                            tv_y_time.text= ""
                            tv_y_time01.text=""
                        })
                    }
                }catch (e:Exception){
                }
            }
        })
        iv_close1.setOnClickListener({
            i=1
        })
        rb__order_time01.text=ClassCalendar.getStringVenueOrder(0)
        rb__order_time02.text=ClassCalendar.getStringVenueOrder(1)
        rb__order_time03.text=ClassCalendar.getStringVenueOrder(2)
        rb__order_time04.text=ClassCalendar.getStringVenueOrder(3)
        rb__order_time05.text=ClassCalendar.getStringVenueOrder(4)
        rb__order_time06.text=ClassCalendar.getStringVenueOrder(5)
        rb__order_time07.text=ClassCalendar.getStringVenueOrder(6)
        tab_order_menu.check(R.id.rb__order_time01)
        val stringExtra = intent.getStringExtra("student_no")
        val student = CardDao.queryStudentId(stringExtra)
        if (student.size!=0){
            tv_order_jf.text =student[0].score+"积分"
        }
        OkhttPost.Okget(API. VENUEGROUPLIST + Constant.SNO+"/"+stringExtra, 1, object : OkhttPost.Callback {
            override fun onError(call: Call?, e: java.lang.Exception?, id: Int) {
            }
            override fun onResponse(response: String?, id: Int) {
              val gson=  Gson()
                val group = gson.fromJson(response, GroupBean::class.java)
                if (group.code==1){
                    lists+=group.data
                    adapterOrder= VenueOrderAdapter2(this@VenueOrderActivity,lists)
                    gv_venue_s.adapter=adapterOrder
                    gv_venue_s.setOnItemClickListener { adapterView, view, po, l ->
                        for(i in 0 until group.data.size){
                            if (i==po){
                                lists[i].setGroup(true)
                                group_id= lists[i].id
                                group_name=lists[i].groupname
                            }else{
                                lists[i].setGroup(false)
                            }
                        }
                        if (t!=po){
//                            Log.e("ATG","进来fali")
                            listUser.clear()
                            listUser+= filledData(lists[po].users)
                            for (s:GroupBean.Users in listUser){
                            Log.e("ATG",s.student_no)
                        }
                            t=po
                        }
//
                        showVenueOrder(applicationContext,po,lists[po].groupname)
                        adapterOrder!!.notifyDataSetChanged()

                    }
                }
            }

        })

        val list1= CardDao.queryComplaint("1")
        val adapterContent=VenueComplaintContentAdapter(this,list1)
        gv_venue_t.adapter=adapterContent
        gv_venue_t.setOnItemClickListener { adapterView, view, i, l ->
            et_order.setText(list1[i].text)
        }
        bt_ti.setOnClickListener({
//            &venue_id=1&booker=6141&group_id=8&start_time=2018-03-15%2011:00&end_time=2018-03-15%2012:00&members[]=1457&members[]=5806
            val str=StringBuffer()
            var num=0
           for (group:GroupBean.Users in listUser){
//               Log.e("ATG",group.student_no+"  预约")
               if (group.isUser){
                   str.append("&members[]=")
                   str.append(group.student_no)
                   ++num
               }
           }
            Log.e("ATG",API. VENUEbooking + Constant.SNO+"&venue_id="+venue_id+"&booker="+venue_student+"&group_id="+group_id+"&start_time="+  VenueOrderTime+
                    "  "+tv_y_time.text.toString()+"&end_time="+VenueOrderTime+" "+tv_y_time01.text.toString()+str.toString())
            DialogUtlis().showYDialog(applicationContext,venue_id,group_id,VenueOrderTime,tv_y_time.text.toString(),tv_y_time01.text.toString(),str.toString(),venue_name,venue_num,group_name,et_order.text.toString(),venue_student,et_order.text.toString())
        })
        Thread(Runnable {
            while (i > 0) {
                handler.sendEmptyMessage(1)
                if (i <= 0) {
                    break
                }
                try {
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                i--
            }
            handler.sendEmptyMessage(2)
        }).start()
    }
    internal var i = 80
    internal var handler: Handler = object : Handler() {
        override fun handleMessage(msg: android.os.Message) {
            if (msg.what == 1) {
//                tv_countdown.text = "还剩" + i + "关闭界面"
                tv_countdown1.text="还剩" + i + "关闭界面"
            } else {

                this@VenueOrderActivity.finish()

            }
        }
    }

    private var num = 0
    internal var is_select = true
    internal var is_select1 = false
    var isuser=true
    fun showVenueOrder(context: Context, po: Int,name:String) {
        var j=20
        num=0
        val list=ArrayList<GroupBean.Users>()
        val inflater = LayoutInflater.from(context)
        val view = inflater.inflate(R.layout.dialog_venue_order, null)
        val gv_dialog_venue = view.findViewById<MyGridView>(R.id.gv_dialog_venue)
        val tv_name = view.findViewById<TextView>(R.id.tv_name)
        val tv_venue_num = view.findViewById<TextView>(R.id.tv_venue_num)
        val tv_close = view.findViewById<TextView>(R.id.tv_close)
        val bt_select = view.findViewById<Button>(R.id.bt_select)
        val bt_sc = view.findViewById<Button>(R.id.bt_sc)
        list.clear()
        tv_name.text=name
        tv_venue_num.text = num.toString()
        listUser.indices
                .filter { listUser[it].isUser }
                .forEach { ++num }
        tv_venue_num.text = num .toString()
//        for (i in list.indices) {
//            listUser[i].setUser(false)
//        }

        Collections.sort<GroupBean.Users>(listUser, PinyinComparator())
        if (isuser){
            adapter1 = VenueOrderAdapter1(context, listUser)
        }
        isuser=false
        gv_dialog_venue.adapter = adapter1
        gv_dialog_venue.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
            listUser[i].setUser(!listUser[i].isUser())
            list.add(listUser[i])
            adapter1!!.notifyDataSetChanged()
            if (listUser[i].isUser()) {
                ++num
            } else {
                --num
            }
            tv_venue_num.text = num .toString()
            //                Log.e("ATG","刷新  "+list.get(i).isUser());
        }
        if (is_select1){
            bt_select.setBackgroundResource(R.drawable.shape3)
        }else{
            bt_select.setBackgroundResource(R.drawable.shape5)
        }
        bt_select.setOnClickListener {
            if (is_select) {
                is_select = false
                bt_select.setBackgroundResource(R.drawable.shape3)
                for (i in listUser.indices) {
                    listUser[i].setUser(true)
                    list.clear()
                }
                adapter1!!.notifyDataSetChanged()
                num = listUser.size
                is_select1=true
                tv_venue_num.text = num.toString()
            } else {
                is_select = true
                bt_select.setBackgroundResource(R.drawable.shape5)
                for (i in listUser.indices) {
                    listUser[i].setUser(false)
                    list.clear()
                    list.add(listUser[i])
                }
                adapter1!!.notifyDataSetChanged()
                num = 0
                is_select1=false
                tv_venue_num.text = num.toString()
            }
        }

        val builder = MyDialog(context, 0, 0, view, R.style.dialog)
        builder.window!!.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        builder.setCancelable(false)
        builder.window!!.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
        builder.show()
        Thread(Runnable {
            while (j > 0) {
                context.runOnUiThread {
                    tv_close.text="还剩" + j + "关闭界面"
                }
                if (j <= 0) {
                    break
                }
                try {
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                j--
            }
            builder.dismiss()
        }).start()
        bt_sc.setOnClickListener {
//            for (group:GroupBean.Users in listUser){
//
////                if (group.isUser){
////                    lists[po].setGroup(true)
////                }
//
//            }
            adapterOrder!!.notifyDataSetChanged()
            builder.dismiss() }
    }
    private fun filledData(date: List<GroupBean.Users>): List<GroupBean.Users> {
        val mSortList = java.util.ArrayList<GroupBean.Users>()
        for (i in date.indices) {
            val sortModel = GroupBean.Users()
            sortModel.setName(date[i].name)
            sortModel.setStudent_no(date[i].student_no)
            val pinyin = PinyinUtils.getPingYin(date[i].getName())
            val sortString = pinyin.substring(0, 1).toUpperCase()
            if (sortString.matches("[A-Z]".toRegex())) {
                sortModel.sortLetters = sortString.toLowerCase()
            }
            mSortList.add(sortModel)
        }
        //        Collections.sort(indexString);
        //        sideBar.setIndexText(indexString);
        return mSortList
    }
    val list=ArrayList<VenueBean.ClassHour>()
    val lists=ArrayList<GroupBean.Data>()
    val listUser=ArrayList<GroupBean.Users>()
    var adapter:FVenueOrderAdapter?=null
    var adapter1:VenueOrderAdapter1?=null
    var adapterOrder:VenueOrderAdapter2?=null
   fun setOk(gson:Gson,id:String,time:String){
       OkhttPost.Okget(API.VENUEDETAIL + Constant.SNO+"/"+id+"/"+time, 2, object : OkhttPost.Callback{
           override fun onError(call: Call, e: Exception, id: Int) {

           }
           override fun onResponse(response: String, id: Int) {
               Log.e("ATG",response)
               val classHour = gson.fromJson(response, VenueBean::class.java)
//                            Log.e("ATG",classHour.data.venue_info.class_hour[0].start_time)

               if (classHour.code==1){
                   if (classHour.data.venue_info.time_type.equals("1")){
                       list+= classHour.data.venue_info.class_hour
                       adapter= FVenueOrderAdapter(this@VenueOrderActivity,list)
                       gv_f_venue.adapter=adapter
                       getGridViewClick(classHour)
                   }else{

                   }
               }
           }
       })
   }
    fun getGridViewClick(classHour:VenueBean){
        gv_f_venue.setOnItemClickListener { adapterView, view, po, l ->
            if (list[po].status == "0"){
                if(!list[po].isVenue){
                    when (po) {
                        0 -> {
                            if (list[po+1].isVenue){
                                (po+1 until list.size)
                                        .filter { list[it].isVenue }
                                        .forEach { tv_y_time01.text=list[it].end_time }
                                list[po].setVenue(true)
                                tv_y_time.text= list[po].start_time
//                                tv_y_time01.text=list[po+1].end_time
                            }else{
                                for (i in 0 until list.size) {
                                    list[i].setVenue(false)
                                }
                                tv_y_time.text= list[po].start_time
                                tv_y_time01.text=list[po].end_time
                            }
                            list[po].setVenue(true)
                        }
                        list.size-1 -> {
                            if (list[po-1].isVenue){
                                list[po].setVenue(true)
                                tv_y_time01.text=list[po].end_time
                            }else{
                                for (i in 0 until list.size) {
                                    list[i].setVenue(false)
                                }
                                tv_y_time.text= list[po].start_time
                                tv_y_time01.text=list[po].end_time
                            }
                            list[po].setVenue(true)
                        }
                        else -> {
                            when {
                                list[po-1].isVenue ->{
                                    list[po].setVenue(true)
//                                  tv_y_time.text= list[po-1].start_time
                                    tv_y_time01.text=list[po].end_time
                                }
                                list[po+1].isVenue -> {
                                    list[po].setVenue(true)

                                    tv_y_time.text= list[po].start_time
//                                    tv_y_time01.text=list[po+1].end_time
                                }
                                else ->{
                                    for (i in 0 until classHour.data.venue_info.class_hour.size) {
                                        list[i].setVenue(false)
                                    }
                                    tv_y_time.text= list[po].start_time
                                    tv_y_time01.text=list[po].end_time
                                }
                            }
                            list[po].setVenue(true)
                        }
                    }
                }else {
                    when(po){
                        0->{
                            if (list[po+1].isVenue){
                                (po+1 until list.size)
                                        .filter { list[it].isVenue }
                                        .forEach { tv_y_time01.text=list[it].end_time }
                                tv_y_time.text= list[po+1].start_time
//                                tv_y_time01.text=list[po+1].end_time
                            }else{
                                tv_y_time.text= ""
                                tv_y_time01.text=""
                            }
                            list[po].setVenue(false)
                        }
                        list.size-1 -> {
                            if (list[po-1].isVenue){
                                for (i in po-1 downTo 0) {
                                    if (list[i].isVenue){
                                        Log.e("ATG","999   "+i)
                                        tv_y_time.text= list[i].start_time
                                    }
                                }
//                                tv_y_time.text= list[po-1].start_time
                                tv_y_time01.text=list[po-1].end_time
                            }else{
                                tv_y_time.text= ""
                                tv_y_time01.text=""
                            }
                            list[po].setVenue(false)
                        }
                        else ->{
                            if (list[po-1].isVenue&&list[po+1].isVenue){
                                for (i in po until list.size) {
                                    list[i].setVenue(false)
                                }
//                              list[po+1].setVenue(false)
                                tv_y_time.text= list[po-1].start_time
                                tv_y_time01.text=list[po-1].end_time
                            }else if (list[po-1].isVenue){
                                tv_y_time01.text=list[po-1].end_time
                                (po-1 downTo 1)
                                        .filter { list[it].isVenue }
                                        .forEach { tv_y_time.text= list[it].start_time }
                                list[po].setVenue(false)
                            }else if(list[po+1].isVenue){
                                (po+1 until list.size)
                                        .filter { list[it].isVenue }
                                        .forEach { tv_y_time01.text=list[it].end_time }
                                list[po].setVenue(false)
                                tv_y_time.text= list[po+1].start_time
//                                tv_y_time01.text=list[po+1].end_time
                            }else{
                                list[po].setVenue(false)
                                tv_y_time.text= ""
                                tv_y_time01.text=""
                            }
                        }
                    }
                }
                adapter!!.notifyDataSetChanged()
            }
        }
    }
    fun getOk(gson:Gson,id:String,time:String){
        OkhttPost.Okget(API.VENUEDETAIL + Constant.SNO+"/"+id+"/"+time, 2, object : OkhttPost.Callback{
            override fun onError(call: Call, e: Exception, id: Int) {

            }
            override fun onResponse(response: String, id: Int) {
                Log.e("ATG",response)
                val classHour = gson.fromJson(response, VenueBean::class.java)
//              Log.e("ATG",classHour.data.venue_info.class_hour[0].start_time)
                if (classHour.code==1){
                    list.clear()
                    list+= classHour.data.venue_info.class_hour


                    getGridViewClick(classHour)
                    adapter!!.notifyDataSetChanged()
                }
            }
        })
    }

    override fun onDestroy() {
        unregisterReceiver(record)
        super.onDestroy()
    }
    var record:OrderReceiver1?=null
    /**
     * 广播类
     */
    inner class OrderReceiver1 : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when(action){
                Constant.ORDER->{
                    DialogUtlis().dismiss()
                    i=2
                }
            }
        }
    }
    /**
     * @return IntentFilter 广播
     */
    private fun filter(): IntentFilter {
        val filter = IntentFilter()
        filter.addAction(Constant.ORDER)
        return filter
    }
}
